import React, { useState, useEffect } from "react";
import { 
  IonPage, 
  IonHeader, 
  IonToolbar, 
  IonTitle, 
  IonContent, 
  IonList, 
  IonItem, 
  IonLabel, 
  IonNote, 
  IonButton, 
  IonIcon, 
  IonFab, 
  IonFabButton, 
  IonModal, 
  IonInput, 
  IonDatetime, 
  IonSelect, 
  IonSelectOption, 
  IonText,
  IonCard,
  IonCardHeader,
  IonCardTitle,
  IonCardContent,
  IonGrid,
  IonRow,
  IonCol,
  IonButtons,
  IonProgressBar,
  useIonAlert
} from "@ionic/react";
import { 
  add, 
  trash, 
  create, 
  chevronDown, 
  chevronUp,
  statsChart,
  body,
  close,
  checkmark
} from 'ionicons/icons';
import { Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import './WeightPage.css';

// 注册Chart.js组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

/* 体重记录 */
interface WeightItem {
  id: string;
  weight: number;
  unit: 'kg' | 'lb';
  date: string;
  notes?: string;
}

const WeightPageAi = () => {
  const [weightRecords, setWeightRecords] = useState<WeightItem[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [editingRecord, setEditingRecord] = useState<WeightItem | null>(null);
  const [newWeight, setNewWeight] = useState<string>('');
  const [newUnit, setNewUnit] = useState<'kg' | 'lb'>('kg');
  const [newDate, setNewDate] = useState<string>(new Date().toISOString());
  const [newNotes, setNewNotes] = useState<string>('');
  const [showChart, setShowChart] = useState(false);
  const [presentAlert] = useIonAlert();
  
  // 初始化一些示例数据
  useEffect(() => {
    const sampleData: WeightItem[] = [
      {
        id: '1',
        weight: 65.5,
        unit: 'kg',
        date: '2023-06-15T10:30:00',
        notes: '晨起空腹'
      },
      {
        id: '2',
        weight: 66.2,
        unit: 'kg',
        date: '2023-06-20T09:45:00',
        notes: '运动后'
      },
      {
        id: '3',
        weight: 64.8,
        unit: 'kg',
        date: '2023-06-25T08:15:00',
        notes: '早餐前'
      }
    ];
    setWeightRecords(sampleData);
  }, []);

  // 添加新记录
  const handleAddRecord = () => {
    if (!newWeight || isNaN(parseFloat(newWeight))) {
      return;
    }
    
    const newRecord: WeightItem = {
      id: Date.now().toString(),
      weight: parseFloat(newWeight),
      unit: newUnit,
      date: newDate,
      notes: newNotes
    };
    
    setWeightRecords([newRecord, ...weightRecords]);
    resetForm();
    setShowModal(false);
  };

  // 更新记录
  const handleUpdateRecord = () => {
    if (!editingRecord || !newWeight || isNaN(parseFloat(newWeight))) {
      return;
    }
    
    const updatedRecords = weightRecords.map(record => 
      record.id === editingRecord.id 
        ? { 
            ...record, 
            weight: parseFloat(newWeight),
            unit: newUnit,
            date: newDate,
            notes: newNotes
          } 
        : record
    );
    
    setWeightRecords(updatedRecords);
    resetForm();
    setShowModal(false);
  };

  // 删除记录
  const handleDeleteRecord = (id: string) => {
    presentAlert({
      header: '删除记录',
      message: '确定要删除这条体重记录吗？',
      buttons: [
        { text: '取消', role: 'cancel' },
        { 
          text: '删除', 
          handler: () => {
            setWeightRecords(weightRecords.filter(record => record.id !== id));
          }
        }
      ]
    });
  };

  // 编辑记录
  const handleEditRecord = (record: WeightItem) => {
    setEditingRecord(record);
    setNewWeight(record.weight.toString());
    setNewUnit(record.unit);
    setNewDate(record.date);
    setNewNotes(record.notes || '');
    setShowModal(true);
  };

  // 重置表单
  const resetForm = () => {
    setEditingRecord(null);
    setNewWeight('');
    setNewUnit('kg');
    setNewDate(new Date().toISOString());
    setNewNotes('');
  };

  // 计算体重变化
  const calculateProgress = () => {
    if (weightRecords.length < 2) return 0;
    
    const sortedRecords = [...weightRecords].sort((a, b) => 
      new Date(a.date).getTime() - new Date(b.date).getTime()
    );
    
    const firstWeight = sortedRecords[0].weight;
    const lastWeight = sortedRecords[sortedRecords.length - 1].weight;
    
    return ((firstWeight - lastWeight) / firstWeight) * 100;
  };

  // 准备图表数据
  const prepareChartData = () => {
    const sortedRecords = [...weightRecords].sort((a, b) => 
      new Date(a.date).getTime() - new Date(b.date).getTime()
    );
    
    const labels = sortedRecords.map(record => 
      new Date(record.date).toLocaleDateString()
    );
    
    const data = sortedRecords.map(record => record.weight);
    
    return {
      labels,
      datasets: [
        {
          label: '体重变化 (kg)',
          data,
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.5)',
          tension: 0.3,
        },
      ],
    };
  };

  // 获取最新体重
  const getLatestWeight = () => {
    if (weightRecords.length === 0) return null;
    
    const sortedRecords = [...weightRecords].sort((a, b) => 
      new Date(b.date).getTime() - new Date(a.date).getTime()
    );
    
    return sortedRecords[0];
  };

  // 获取目标进度
  const getGoalProgress = () => {
    // 假设目标体重为60kg
    const goalWeight = 60;
    const latest = getLatestWeight();
    
    if (!latest) return 0;
    
    const currentWeight = latest.weight;
    // 假设起始体重为70kg
    const startWeight = 70;
    
    const totalToLose = startWeight - goalWeight;
    const currentLost = startWeight - currentWeight;
    
    return (currentLost / totalToLose) * 100;
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>体重记录</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent className="ion-padding">
        {/* 统计卡片 */}
        {weightRecords.length > 0 && (
          <IonCard className="stats-card">
            <IonCardHeader>
              <IonCardTitle>体重统计</IonCardTitle>
            </IonCardHeader>
            <IonCardContent>
              <IonGrid>
                <IonRow>
                  <IonCol size="6">
                    <div className="stat-item">
                      <IonText color="medium">当前体重</IonText>
                      <IonText className="stat-value">
                        {getLatestWeight()?.weight} {getLatestWeight()?.unit}
                      </IonText>
                    </div>
                  </IonCol>
                  <IonCol size="6">
                    <div className="stat-item">
                      <IonText color="medium">变化趋势</IonText>
                      <IonText className="stat-value">
                        {calculateProgress().toFixed(1)}%
                        {calculateProgress() > 0 ? (
                          <IonIcon icon={chevronDown} color="success" />
                        ) : (
                          <IonIcon icon={chevronUp} color="danger" />
                        )}
                      </IonText>
                    </div>
                  </IonCol>
                </IonRow>
                
                <IonRow>
                  <IonCol>
                    <div className="goal-progress">
                      <IonText color="medium">目标进度 (60kg)</IonText>
                      <IonProgressBar 
                        value={getGoalProgress() / 100} 
                        color="success"
                      />
                      <IonText className="progress-text">
                        {getGoalProgress().toFixed(1)}%
                      </IonText>
                    </div>
                  </IonCol>
                </IonRow>
              </IonGrid>
            </IonCardContent>
          </IonCard>
        )}
        
        {/* 图表切换按钮 */}
        <div className="chart-toggle">
          <IonButton 
            fill="outline" 
            onClick={() => setShowChart(!showChart)}
          >
            <IonIcon slot="start" icon={statsChart} />
            {showChart ? '隐藏图表' : '显示图表'}
          </IonButton>
        </div>
        
        {/* 体重图表 */}
        {showChart && weightRecords.length > 0 && (
          <div className="chart-container">
            <Line data={prepareChartData()} />
          </div>
        )}
        
        {/* 体重记录列表 */}
        {weightRecords.length > 0 ? (
          <>
            <IonList lines="full" className="record-list">
              {weightRecords.map(record => (
                <IonItem key={record.id} className="record-item">
                  <IonIcon slot="start" icon={body} color="primary" />
                  
                  <IonLabel>
                    <h2>{record.weight} {record.unit}</h2>
                    <IonNote>
                      {new Date(record.date).toLocaleDateString()} · {record.notes}
                    </IonNote>
                  </IonLabel>
                  
                  <IonButton 
                    fill="clear" 
                    slot="end" 
                    color="medium"
                    onClick={() => handleEditRecord(record)}
                  >
                    <IonIcon icon={create} />
                  </IonButton>
                  
                  <IonButton 
                    fill="clear" 
                    slot="end" 
                    color="danger"
                    onClick={() => handleDeleteRecord(record.id)}
                  >
                    <IonIcon icon={trash} />
                  </IonButton>
                </IonItem>
              ))}
            </IonList>
          </>
        ) : (
          <EmptyPage />
        )}

        {/* 添加记录按钮 */}
        <IonFab vertical="bottom" horizontal="end" slot="fixed">
          <IonFabButton color="primary" onClick={() => {
            resetForm();
            setShowModal(true);
          }}>
            <IonIcon icon={add} />
          </IonFabButton>
        </IonFab>

        {/* 添加/编辑记录模态框 */}
        <IonModal isOpen={showModal} onDidDismiss={() => setShowModal(false)}>
          <IonHeader>
            <IonToolbar>
              <IonTitle>
                {editingRecord ? "编辑体重记录" : "添加体重记录"}
              </IonTitle>
              <IonButtons slot="end">
                <IonButton onClick={() => setShowModal(false)}>
                  <IonIcon icon={close} />
                </IonButton>
              </IonButtons>
            </IonToolbar>
          </IonHeader>
          <IonContent className="ion-padding">
            <div className="form-container">
              <IonItem>
                <IonLabel position="stacked">体重</IonLabel>
                <IonInput
                  type="number"
                  value={newWeight}
                  onIonChange={e => setNewWeight(e.detail.value!)}
                  placeholder="请输入体重"
                />
                <IonSelect 
                  value={newUnit} 
                  onIonChange={e => setNewUnit(e.detail.value)}
                  interface="popover"
                >
                  <IonSelectOption value="kg">kg</IonSelectOption>
                  <IonSelectOption value="lb">lb</IonSelectOption>
                </IonSelect>
              </IonItem>
              
              {/* <IonItem>
                <IonLabel position="stacked">日期</IonLabel>
                <IonDatetime
                  value={newDate}
                  onIonChange={e => setNewDate(e.detail.value!)}
                  presentation="date"
                />
              </IonItem> */}
              
              <IonItem>
                <IonLabel position="stacked">备注</IonLabel>
                <IonInput
                  value={newNotes}
                  onIonChange={e => setNewNotes(e.detail.value!)}
                  placeholder="例如：晨起空腹、运动后等"
                />
              </IonItem>
              
              <IonButton 
                expand="block" 
                className="submit-button"
                onClick={editingRecord ? handleUpdateRecord : handleAddRecord}
              >
                <IonIcon slot="start" icon={checkmark} />
                {editingRecord ? "更新记录" : "添加记录"}
              </IonButton>
            </div>
          </IonContent>
        </IonModal>
      </IonContent>
    </IonPage>
  );
};

const EmptyPage = () => (
  <div className="empty-state">
    <IonIcon icon={body} size="large" color="medium" />
    <h3>暂无体重记录</h3>
    <p>点击右下角按钮，添加您的第一条体重记录</p>
  </div>
);

export default WeightPageAi;